#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

using namespace std;

namespace client
{
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        CONNECT_ERR
    };

#define NUM 1024

    class TcpClient
    {
    public:
        TcpClient(const string &serverip, uint16_t &serverport)
            : _sock(-1), _serverip(serverip), _serverport(serverport)
        {
        }

        ~TcpClient()
        {
            if(_sock >= 0)
                close(_sock);
        }

        void initClient()
        {
            // 1. 创建socket
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if (_sock < 0)
            {
                cerr << "create socket err!" << endl;
                exit(SOCKET_ERR);
            }

            // 2. tcp的客户端要不要bind？要的！ 要不要显式的bind？不要！这里尤其是client port要让OS自动随机指定！
            // 3. 要不要listen？不要！
            // 4. 要不要accept? 不要！
            // 5. 要什么呢？？要发起链接！
        }

        void start()
        {
            // 2. 发起链接
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            if(connect(_sock, (struct sockaddr*)&server, sizeof(server)) < 0)
            {
                cerr << "connect error!" << endl;
                exit(CONNECT_ERR);
            }

            char buffer[NUM];
            while(true)
            {
                cout << "Please Enter# ";

                string msg;
                getline(cin, msg);

                write(_sock, msg.c_str(), msg.size());

                int n = read(_sock, buffer, sizeof(buffer) - 1);
                if(n > 0)
                {
                    buffer[n] = 0;
                    cout << "Server回显-> " << buffer << endl;
                }
                else if(n == 0)
                {
                    cout << "server quit! me too!" << endl;
                    break;
                }
            }
        }

    private:
        int _sock;
        string _serverip;
        uint16_t _serverport;
    };

} // namespace client
